<?php
namespace system\service;

use herosphp\cache\CacheFactory;
use system\service\interfaces\IOperationService;
use common\service\CommonService;
use herosphp\core\Loader;

Loader::import('system.service.interfaces.IOperationService');

/**
 * system(Service)接口实现
 * @package system\service
 * @author yangjian<yangjian102621@gmail.com>
 */
class OperationService extends CommonService implements IOperationService {

    /**
     * 获取权限数组
     * @return mixed
     */
    public function getPermssionArray()
    {
        $CACHER = CacheFactory::create('file');
        if ( $CACHER->get(self::PERMISSION_DATA_CACHE) == false ) {
            $this->flush();
        }
        return $CACHER->get(self::PERMISSION_DATA_CACHE);
    }

    //分组获取所有可用操作
    public function getOperationsByGroup() {
        $CACHER = CacheFactory::create('file');
        if ( $CACHER->get(self::OPERATION_DATA_CACHE) == false ) {
            $this->flush();
        }
        return $CACHER->get(self::OPERATION_DATA_CACHE);
    }

    /**
     * 刷新权限数组缓存
     * @return mixed
     */
    public function flush()
    {
        //1. 组建分组操作数据
        $items = $this->field('module')->group('module')->find();
        $__items = array();
        $moduleNames = LANG('PERMISSION_MODULE_NAME');
        foreach ($items as $value) {
            $arr['module'] = $value['module'];
            $arr['name'] = $moduleNames[$value['module']];
            $arr['items'] = $this->where(array('module' => $value['module']))
                ->sort(array('optkey' => 1))
                ->find();
            $__items[] = $arr;

        }

        //2. 组建权限数组
        $operations = $this->getItems();
        $__permissions = array();
        foreach ( $operations as $v ) {
            $__permissions[$v['optkey']] = 1;
        }

        $CACHER = CacheFactory::create('file');
        $CACHER->set(self::OPERATION_DATA_CACHE, $__items, 0);
        $CACHER->set(self::PERMISSION_DATA_CACHE, $__permissions, 0);
    }
}
